package com.pgm.controller;


import com.pgm.model.UserInfo;
import com.pgm.model.VisitUserInfo;
import com.pgm.service.IndexService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;

@RestController
public class IndexController {


    @Autowired
    IndexService indexService;
    @RequestMapping("/index")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return  modelAndView;
    }

    /**COB
     *
     * @return
     */
    @RequestMapping("/cob")
    public List<UserInfo> cob(String userNoOrUsername){
        return  indexService.cob(userNoOrUsername);
    }
    @RequestMapping("/device")
    public List<UserInfo> device(String userNoOrUsername){
        return  indexService.device(userNoOrUsername);
    }
    @RequestMapping("/restArea")
    public List<UserInfo> restArea(String userNoOrUsername){
        return  indexService.restArea(userNoOrUsername);
    }





    @RequestMapping("/peopleCounting")
    public Map<String,Integer> peopleCounting(){
        return  indexService.peopleCounting();
    }



    @RequestMapping("/exportExcel")
    public void buildExcelDocument(HttpServletRequest request, HttpServletResponse response) throws Exception{
        try {
            String fileName = "AO装置访问记录"+System.currentTimeMillis()+".xls";
            // 各浏览器基本都支持ISO编码
            String userAgent = request.getHeader("User-Agent").toUpperCase();
            if (userAgent.contains("TRIDENT") || userAgent.contains("EDGE")) {
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else if (userAgent.contains("MSIE")) {
                fileName = new String(fileName.getBytes(), "ISO-8859-1");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }

            response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName));
            OutputStream os = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            //将excel写入到输出流中
            HSSFWorkbook workbook = indexService.exportExcel();
            workbook.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
